<template>
  <el-dialog
    v-model="visible"
    title="修改登录密码"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="password-form"
    >
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="formData.phone"
          placeholder="请输入手机号码"
          maxlength="11"
          disabled
        />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div class="verify-code-input">
          <el-input
            v-model="formData.code"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <el-button
            type="primary"
            :disabled="!!timer"
            @click="handleGetVerifyCode"
          >
            {{ timer ? `${countdown}s后重新获取` : "获取验证码" }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="formData.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { captchaSMSByTrading, captchaSMS } from "@/api/system";
import { useNav } from "@/layout/hooks/useNav";
const visible = ref(false);
const formRef = ref<FormInstance>();
const timer = ref<number | null>(null);
const countdown = ref(60);
const { username, userPhone } = useNav();

const formData = reactive({
  phone: "",
  code: "",
  newPassword: "",
  confirmPassword: "",
  originUuid:""
});

onMounted(() => {
  formData.phone = userPhone;
  //清除之前数据
  handleClose();
});

const validatePhone = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请输入手机号码"));
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error("请输入正确的手机号码"));
  } else {
    callback();
  }
};

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== formData.newPassword) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  verifyCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 6, max: 6, message: "验证码长度为6位", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{8,20}$/,
      message: "密码必须包含8-20位数字和英文大小写",
      trigger: "blur"
    }
  ],
  confirmPassword: [{ validator: validatePass, trigger: "blur" }]
});

const startCountdown = () => {
  countdown.value = 60;
  timer.value = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      if (timer.value) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }
  }, 1000);
};

const handleGetVerifyCode = async () => {
  try {
    await formRef.value?.validateField("phone");
    const res = await captchaSMSByTrading();
    if (res.code === 200) {
      ElMessage.success("验证码已发送");
      formData.originUuid = res.data
      startCountdown();
    } else {
      ElMessage.error(res.msg || "验证码发送失败");
    }
  } catch (error) {
    // 验证未通过
  }
};

const handleConfirm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    // TODO: 调用修改密码接口
    const res = await captchaSMS({
      code: formData.code,
      newPassword: formData.newPassword,
      newAgainPassword: formData.confirmPassword,
      type: 0,
      originUuid: formData.originUuid
    });
    if (res.code == 200) {
      ElMessage.success("密码修改成功");
      handleClose();
    }
  } catch (error) {
    // 验证未通过
  }
};

const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

defineExpose({
  visible
});
</script>

<style scoped>
.password-form {
  padding: 20px;
}

.verify-code-input {
  display: flex;
  gap: 8px;
}

.verify-code-input .el-button {
  flex-shrink: 0;
  width: 120px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
